package com.geline.mybatisplus.interceptor.inner;

import com.baomidou.mybatisplus.extension.plugins.inner.InnerInterceptor;
import com.geline.cloud.core.BaseTimedCache;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.mapping.SqlCommandType;

import java.sql.SQLException;

/**
 * 定时缓存清理
 *
 * @author: mx
 * @date: 2024-09-05 14:47
 */
@Slf4j
public class CacheClearInterceptor implements InnerInterceptor {

    private BaseTimedCache timedCache;

    public CacheClearInterceptor(BaseTimedCache timedCache){
        this.timedCache = timedCache;
    }

    @Override
    public boolean willDoUpdate(Executor executor, MappedStatement ms, Object parameter) throws SQLException {
        SqlCommandType sct = ms.getSqlCommandType();
        if (sct == SqlCommandType.INSERT || sct == SqlCommandType.UPDATE || sct == SqlCommandType.DELETE) {
            int size = timedCache.keySet().size();
            //清空缓存
            timedCache.clear();
            log.info("success to clear BaseTimedCache key.size = {}", size);
        }
        return true;
    }
}
